/* Copyright Wenky. */
package com.spring.app.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.Future;

import javax.inject.Inject;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.io.IOUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.spring.app.genpostagelabel.Utils;


/**
 * @author venkatesh
 */
@Component
public class EmailSenderService {
    @Inject
    private Environment environment;
    @Autowired
    JavaMailSender javaMailSender;
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(EmailSenderService.class);

    
    

    /**
     * Sends emails with attachments
     *
     * @param from
     * @param to
     * @param subject
     * @param attachments
     */
    @Async
    public Future<Boolean> sendEmailWithAttachments(String to, String body,
                                         String subject,String attachment,
                                         String[] bcc) {
        try {
                  MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = null;
            try {
                helper = new MimeMessageHelper(message, true);
                helper.setText(body, true);
            } catch (MessagingException e1) {
                e1.printStackTrace();
            }

            try {
            	helper.setFrom("wenky@ebayinventory.com");
                helper.setTo(to);
                helper.setSubject(subject);
                if (!Utils.isEmpty(bcc))
                    helper.setBcc(bcc);
            } catch (MessagingException e) {
                logger.error(e.toString());
                e.printStackTrace();
            }

           helper.addAttachment(attachment.substring(attachment.lastIndexOf("\\")+1),new File(attachment));
            javaMailSender.send(message);
            System.out.println("EMAil sent...");
            return new AsyncResult<Boolean>(true);
        } catch (MessagingException e) {
            logger.error(e.toString());
            e.printStackTrace();
        } catch (Throwable e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return new AsyncResult<Boolean>(false);
    }

}